<template>
  <div class="rec-bg">
    <aside class="sidebar">
      <div class="logo">
        <img class="logo-img" src="/logo.png" alt="光影漫荐 Logo" onerror="this.style.display='none'" />
        <span class="logo-text">光影漫荐</span>
      </div>
      <nav>
        <router-link class="nav-item" exact-active-class="active" to="/recommend">首页</router-link>
        <router-link class="nav-item" exact-active-class="active" to="/hot">热门电影</router-link>
        <router-link class="nav-item" exact-active-class="active" to="/movies">全部电影</router-link>
        <router-link class="nav-item" exact-active-class="active" to="/watchlist">我的片单</router-link>
        <router-link class="nav-item" exact-active-class="active" to="/user-ratings">我的评分</router-link>
      </nav>
    </aside>
    <main class="main-content">
      <header class="header">
        <div class="header-title">为你推荐</div>
        <!-- 搜索框 -->
        <div class="header-search">
          <input
            v-model="searchKeyword"
            type="text"
            class="search-input"
            placeholder="搜索电影名称…"
            @keyup.enter="submitSearch"
            aria-label="搜索电影"
          />
          <button class="search-btn" @click="submitSearch" aria-label="执行搜索">搜索</button>
        </div>
        <div class="header-user">
          <template v-if="isAuthed">
            <span>欢迎，用户<span v-if="userCode"> {{ userCode }}</span></span>
            <button class="btn-logout" @click="logout">退出登录</button>
          </template>
          <template v-else>
            <button class="btn-auth" @click="goLogin">登录</button>
            <button class="btn-auth" @click="goRegister">注册</button>
          </template>
        </div>
      </header>
      
      <!-- 主推电影海报 -->
      <div class="featured-movie">
        <div 
          class="featured-bg"
          :style="featuredBgStyle"
        ></div>
        <div class="featured-info">
          <div class="featured-title">{{ featuredMovie.title }}</div>
          <div class="featured-desc">{{ featuredMovie.description }}</div>
          <div class="featured-actions">
              <button class="btn-play" @click="playMovie(featuredMovie.id)">▶ 立即播放</button>
              <button class="btn-add" @click="addToWatchlist(featuredMovie.id)">{{ featuredAddedLabel }}</button>
          </div>
        </div>
      </div>
      
      <!-- 热门电影推荐 -->
      <section class="movie-section">
        <div class="section-title">
          <span>热门电影</span>
          <a href="#" class="view-all" @click.prevent="viewAll('hot')">查看全部 ></a>
        </div>
        <div class="movie-list">
          <MovieCard 
            v-for="movie in hotMoviesTop7" 
            :key="movie.id" 
            :movie="movie"
            @select="goToDetail"
          />
        </div>
      </section>
      
      <!-- 加入片单提示弹窗 -->
      <InfoDialog
        :show="showJoinDialog"
        :title="joinDialogTitle"
        :message="joinDialogMessage"
        primaryText="确定"
        @close="showJoinDialog = false"
        @primary="showJoinDialog = false"
      />
      
      
    </main>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import MovieCard from '../components/MovieCard.vue'
import InfoDialog from '@/components/InfoDialog.vue'
import { fetchHotMovies } from '../services/movie.js'
import { hotMoviesCache } from '@/services/cache.js'
import { watchlistService } from '@/services/watchlist.js'

export default {
  name: 'RecommendPage',
  components: { 
    MovieCard,
    InfoDialog
  },
  setup() {
  // 登录态与编号展示
  const token = ref(null)
  const userCode = ref('')
  const isAuthed = computed(() => !!token.value)
  const router = useRouter()
  const searchKeyword = ref('')
    
    // featured 区域由接口数据首项驱动，优先使用横屏图(backdrop)，再回退到海报图
  const featuredMovie = ref({ id: null, title: '', description: '', backdrop: '', poster: '' })
  const featuredInWatchlist = ref(false)
  const featuredAddedLabel = computed(() => featuredInWatchlist.value ? '已加入' : '+ 加入片单')
    
  const hotMovies = ref([])
  const hotMoviesTop7 = computed(() => hotMovies.value.slice(0, 7))
  
  // 加入片单弹窗状态
  const showJoinDialog = ref(false)
  const joinDialogTitle = ref('加入片单')
  const joinDialogMessage = ref('')

    // 顶部海报背景样式：有图则叠加图片，无图仅用渐变
    const featuredBgStyle = computed(() => {
      const bg = featuredMovie.value.backdrop || featuredMovie.value.poster || ''
      return {
        background: bg
          ? `linear-gradient(to right, #0f0f0f 0%, transparent 50%, #0f0f0f 100%), url('${bg}') center/cover no-repeat`
          : 'linear-gradient(to right, #0f0f0f 0%, #1a1a1a 100%)'
      }
    })

    // 获取热门/推荐电影（从后端）
    async function loadHotMovies() {
      try {
        // 若缓存仍在有效期内，优先使用缓存，避免刷新变动
        const cached = hotMoviesCache.get()
        if (Array.isArray(cached) && cached.length) {
          hotMovies.value = cached
        }
        if (!hotMovies.value.length) {
          const res = await fetchHotMovies()
          const list = Array.isArray(res.data) ? res.data : []
          hotMovies.value = list.map((m, idx) => ({
          id: m.movieId ?? m.id ?? idx, // 兼容后端两种字段
          title: m.title ?? '未知标题',
          rating: Number(m.predicted_rating ?? m.rating_mean ?? (8 + Math.random()).toFixed(1)),
          // 兼容多种字段名：优先横屏图(backdrop/banner/landscape)，再回退到 poster
          poster: m.poster || m.poster_path || '',
          backdrop: m.backdrop || m.backdrop_path || m.banner || m.landscape || m.horizontal_image || '',
          overview: m.overview || '',
          year: m.year || '',
          genres: m.genres || ''
        }))
          // 写入持久缓存（默认 30 分钟），保持热门列表稳定
          hotMoviesCache.set(hotMovies.value)
        }

        // 用第一条推荐作为顶部海报
        if (hotMovies.value.length > 0) {
          const first = hotMovies.value[0]
          featuredMovie.value = {
            id: first.id,
            title: first.title,
            description: first.overview || '',
            backdrop: first.backdrop || first.poster || '',
            poster: first.poster || ''
          }
          // 同步 featured 的片单状态
          try { featuredInWatchlist.value = watchlistService.has(first.id) } catch (_) { featuredInWatchlist.value = false }
        }
      } catch (e) {
        console.error('获取热门电影失败', e)
      }
    }

    function parseJwtUserId(t) {
      try {
        const base64Url = String(t).split('.')[1]
        if (!base64Url) return null
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
        const json = decodeURIComponent(atob(base64).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''))
        const payload = JSON.parse(json)
        return payload?.user_id ?? null
      } catch (_) {
        return null
      }
    }

    function refreshAuthInfo() {
      const t = (typeof window !== 'undefined') ? localStorage.getItem('token') : null
      token.value = t
      // 优先读取登录时保存的5位编号
      let code = (typeof window !== 'undefined') ? localStorage.getItem('user_code') : ''
      if ((!code || code.length < 1) && t) {
        const uid = parseJwtUserId(t)
        const s = uid != null ? String(uid) : ''
        if (s) code = s
      }
      userCode.value = code || ''
    }

    onMounted(() => {
      refreshAuthInfo()
      loadHotMovies()
    })
  
    function playMovie(movieId) {
      if (!movieId) return
      const token = localStorage.getItem('token')
      if (!token) {
        router.push({ path: '/login', query: { redirect: `/player/${movieId}` } })
        return
      }
      router.push(`/player/${movieId}`)
    }

    function addToWatchlist(movieId) {
      const token = localStorage.getItem('token')
      if (!token) {
        router.push({ path: '/login', query: { redirect: router.currentRoute.value.fullPath } })
        return
      }
      if (!movieId) return
      // 在当前热门列表中找到该电影条目
      const movie = hotMovies.value.find(m => String(m.id) === String(movieId)) || featuredMovie.value
      const existed = movie?.id != null ? watchlistService.has(movie.id) : false
      const res = watchlistService.add(movie)
      const title = (movie && movie.title) ? movie.title : `ID ${movieId}`
      if (res && res.ok) {
        joinDialogTitle.value = '加入片单成功'
        joinDialogMessage.value = `“${title}” ${existed ? '已在片单（已更新）' : '已加入片单'}`
        showJoinDialog.value = true
        featuredInWatchlist.value = true
      } else {
        joinDialogTitle.value = '加入片单失败'
        joinDialogMessage.value = `加入片单失败：${title}`
        showJoinDialog.value = true
      }
    }

    function goLogin() {
      router.push('/login')
    }
    function goRegister() {
      router.push('/register')
    }
    function logout() {
      try {
        localStorage.removeItem('token')
        localStorage.removeItem('user_code')
      } catch (_) { void 0 }
      refreshAuthInfo()
      router.push('/login')
    }

    function viewAll(category) {
      if (category === 'hot') {
        // 将已加载的热门电影放入缓存，供热门页复用
        if (hotMovies.value && hotMovies.value.length) {
          hotMoviesCache.set(hotMovies.value)
        }
        router.push({ name: 'hot' })
        return
      }
      router.push('/movies')
    }

    // 触发到“全部电影”页进行标题模糊搜索
    function submitSearch() {
      const q = String(searchKeyword.value || '').trim()
      if (!q) {
        // 无关键词则跳到全部电影
        router.push({ name: 'movies' })
        return
      }
      router.push({ name: 'movies', query: { q } })
    }

    // 点击卡片进入详情页
    function goToDetail(movieId) {
      if (!movieId) return
      router.push({ name: 'movie', params: { id: movieId } })
    }

    // 监听 featured 电影变化与 storage 事件，保持按钮文案同步
    function syncFeaturedAdded() {
      try { featuredInWatchlist.value = watchlistService.has(featuredMovie.value?.id) } catch (_) { featuredInWatchlist.value = false }
    }
    watch(() => featuredMovie.value?.id, () => syncFeaturedAdded())
    function onStorage(e){
      try {
        const key = e?.key || ''
        if (typeof key === 'string' && key.startsWith('watchlist_v1_')) syncFeaturedAdded()
      } catch (_) { void 0 }
    }
    if (typeof window !== 'undefined') window.addEventListener('storage', onStorage)
    onBeforeUnmount(() => { if (typeof window !== 'undefined') window.removeEventListener('storage', onStorage) })

    return { 
  isAuthed,
  userCode,
      featuredMovie,
      hotMovies, 
      featuredBgStyle,
  hotMoviesTop7,
  featuredAddedLabel,
      playMovie,
      addToWatchlist,
      viewAll,
      goToDetail,
      goLogin,
      goRegister,
      logout,
      // search
      searchKeyword,
      submitSearch
      ,
      // dialog
      showJoinDialog,
      joinDialogTitle,
      joinDialogMessage
    }
  }
}
</script>

<style scoped>
.rec-bg {
  min-height: 100vh;
  background: #0f0f0f;
  display: flex;
  color: white;
}

.sidebar {
  width: 200px;
  background: #1c1c1c;
  padding-top: 20px;
  flex-shrink: 0;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 30px;
  padding: 0 20px;
}

.logo-img {
  width: 32px;
  height: 32px;
  object-fit: contain;
  border-radius: 6px;
}

.logo-text {
  font-size: 20px;
  color: #ff4e4e;
  font-weight: bold;
}

.nav-item {
  display: block;
  color: #ccc;
  padding: 12px 20px;
  text-decoration: none;
  font-size: 14px;
  transition: all 0.3s;
  border-left: 3px solid transparent;
  cursor: pointer;
}

.nav-item.active, .nav-item:hover {
  background: #2a2a2a;
  color: #fff;
  border-left-color: #ff4e4e;
}

.main-content {
  flex: 1;
  padding: 20px 30px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  font-size: 24px;
  font-weight: bold;
}

.header-user {
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 10px;
}
/* 右上角文案更显眼 */
.header-user { font-size: 16px; font-weight: 700; }

/* 顶部搜索 */
.header-search { display:flex; align-items:center; gap: 8px; margin-left: auto; margin-right: 16px; }
.search-input {
  width: 260px;
  background: #1f1f1f;
  color: #fff;
  border: 1px solid #333;
  border-radius: 20px;
  padding: 8px 12px;
}
.search-input::placeholder { color: #888; }
.search-btn {
  background: #ff4e4e;
  color: #fff;
  border: none;
  border-radius: 18px;
  padding: 8px 14px;
  cursor: pointer;
  font-weight: 700;
}
.search-btn:hover { filter: brightness(0.95); }

.btn-auth {
  background: #000;
  color: #fff;
  border: 1px solid #fff;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 700;
}
.btn-auth:hover { opacity: .9; }

.btn-logout {
  background: transparent;
  color: #ccc;
  border: 1px solid #444;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 700;
}
.btn-logout:hover { border-color: #666; color: #eee; }

.featured-movie {
  width: 100%;
  height: 640px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  margin-bottom: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.7);
}

.featured-bg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.featured-info {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 30px;
  background: linear-gradient(to top, rgba(0,0,0,0.9) 0%, transparent 100%);
}

.featured-title {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 10px;
}

.featured-desc {
  font-size: 16px;
  color: #ddd;
  max-width: 600px;
  margin-bottom: 20px;
  line-height: 1.5;
}

.featured-actions {
  display: flex;
  gap: 15px;
}

.btn-play {
  background: #ff4e4e;
  color: white;
  border: none;
  padding: 10px 25px;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: background 0.3s;
}

.btn-play:hover {
  background: #ff3333;
}

.btn-add {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: background 0.3s;
}

.btn-add:hover {
  background: rgba(255, 255, 255, 0.3);
}

.movie-section {
  margin-bottom: 40px;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.view-all {
  color: #aaa;
  font-size: 14px;
  text-decoration: none;
  transition: color 0.3s;
}

.view-all:hover {
  color: #ff4e4e;
}

.movie-list {
  display: grid;
  grid-template-columns: repeat(7, 180px);
  justify-content: start;
  gap: 24px;
  padding-bottom: 10px;
}

/* 去掉横向滚动条的样式，改为网格自动换行 */

@media (max-width: 768px) {
  .rec-bg {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    padding: 10px 0;
  }
  
  .nav-item {
    display: inline-block;
    width: auto;
    margin: 0 10px;
    border-left: none;
    border-bottom: 3px solid transparent;
  }
  
  .nav-item.active, .nav-item:hover {
    border-left-color: transparent;
    border-bottom-color: #ff4e4e;
  }
  
  .featured-movie {
    height: 380px;
  }
  
  .featured-title {
    font-size: 24px;
  }
  
  .featured-desc {
    font-size: 14px;
  }
}
</style>